package com.controller;


import com.alibaba.fastjson.JSON;
import com.annotation.SysLog;
import com.attribute.CourseTypeEnum;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.entity.CommentEntity;
import com.entity.CourseEntity;
import com.entity.LessonEntity;
import com.entity.UserEntity;
import com.service.CommentService;
import com.service.UserService;
import com.utils.MPUtil;
import com.utils.OBSUtil;
import com.utils.PageUtils;
import com.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.UUID;


/**
 * 评论控制类
 */
@RestController
@RequestMapping("/comment")
public class CommentController {

    @Autowired
    OBSUtil obsUtil;

    @Autowired
    CommentService commentService;

    @Autowired
    UserService userService;


    /**
     * 新增评论
     * */
    @RequestMapping("/add")
    @SysLog("新增评论")
    public R addComment(@RequestParam("commentData") String commentJsonString, // 接收 JSON 字符串
                        @RequestParam(value = "image", required = false) MultipartFile image, // 接收上传的文件
                        HttpServletRequest request){
        Long userId = (Long) request.getSession().getAttribute("userId"); // 从 session 获取当前登录用户ID
        if (userId == null) {
            return R.error(401, "用户未登录或会话已过期。");
        }
        CommentEntity comment;
        try {
            comment = JSON.parseObject(commentJsonString, CommentEntity.class);
        } catch (Exception e) {
            return R.error("评论数据解析失败: " + e.getMessage());
        }

        comment.setCommentTime(new Date()); // 如果是 java.util.Date

        try {
            if (image != null && !image.isEmpty()) {
                String fileName = "comment/images/" + UUID.randomUUID().toString() + "-" + image.getOriginalFilename();
                String imageUrl = obsUtil.uploadFile(fileName, image.getInputStream());
                comment.setImage(imageUrl);
            }


        } catch (IOException e) {
            return R.error("图片文件上传失败: " + e.getMessage());
        }
        comment.setUserId(userId);
        UserEntity user=userService.selectById(userId);
        comment.setName(user.getName());
        comment.setUserAvatar(user.getAvatar());
        commentService.insert(comment);
        return R.ok("评论成功");
    }

    @PostMapping("/delete")
    public R deleteComment(@RequestBody Map<String, Object> payload, HttpServletRequest request) {
        Long userId = (Long) request.getSession().getAttribute("userId");
        if (userId == null) {
            return R.error(401, "用户未登录或会话已过期。");
        }

        Object commentIdObj = payload.get("commentId");
        if (commentIdObj == null) {
            return R.error("不存在这条评论");
        }

        Long commentId = Long.valueOf(commentIdObj.toString());

        CommentEntity comment = commentService.selectById(commentId);
        if (comment == null) {
            return R.error("不存在这条评论");
        }

        commentService.deleteById(commentId);
        return R.ok("删除成功");
    }


    @RequestMapping("/page")
    public R page(@RequestParam Map<String, Object> params, CommentEntity comment,
                  HttpServletRequest request){
        if (comment.getRating() != null && comment.getRating() == 0) {
            comment.setRating(null);
        }

        EntityWrapper<CommentEntity> ew = new EntityWrapper<CommentEntity>();
        String courseId=(String)params.get("courseId");
        if(courseId!=null){
            ew.eq("course_id",courseId);
        }
        PageUtils page = commentService.queryPage(params, MPUtil.sort(MPUtil.between(MPUtil.likeOrEq(ew, comment), params), params));
        return R.ok().put("data", page);
    }


    /**
     * 用户获取自己的评论
     * */
    @RequestMapping("/getMyComments")
    public R getMyComments(@RequestParam Map<String, Object> params, CommentEntity comment,
                           HttpServletRequest request) {

        Object userIdObj = request.getSession().getAttribute("userId");
        if (userIdObj == null) {
            return R.error(401, "用户未登录或无法获取用户ID");
        }

        Long userId = Long.valueOf(userIdObj.toString());

        // 如果评分为 0，设置为 null，避免影响查询
        if (comment.getRating() != null && comment.getRating() == 0) {
            comment.setRating(null);
        }

        // 构造查询条件
        EntityWrapper<CommentEntity> ew = new EntityWrapper<>();
        ew.eq("user_id", userId);

        // 查询分页数据，包含课程标题
        PageUtils page = commentService.queryPageWithCourseTitle(
                params,
                MPUtil.sort(MPUtil.between(MPUtil.likeOrEq(ew, comment), params), params)
        );

        return R.ok().put("data", page);
    }

}
